package com.zy.design.pattern.di.meat;

import lombok.Data;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaoyi
 * @date 2021/4/1 10:37
 */
@Data
public class ClassMeat {
    private String id;
    private Class clazzName;
    private Scope scope;
    private boolean lazy;
    private List<ConstructorArgs> constructorArgsList = new ArrayList<>();

    //解析出ClassMeat信息,异常说明先不考虑
    public ClassMeat(Element element) throws ClassNotFoundException {
        this.id = element.getAttribute("id");
        this.scope = Scope.valueOf(element.getAttribute("scope"));
        this.lazy = "true".equalsIgnoreCase(element.getAttribute("lazy-init"));
        this.clazzName = Class.forName(element.getAttribute("class"));
        NodeList childNodes = element.getChildNodes();
        for (int j = 0; j < childNodes.getLength(); j++) {
            if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
                //获取节点
                Element item = (Element) childNodes.item(j);
                boolean hasRef = item.hasAttribute("ref");
                ConstructorArgs constructorArgs = null;
                if (hasRef) {
                    String ref = item.getAttribute("ref");
                    constructorArgs = new ConstructorArgs.Builder()
                            .setHasRef(true)
                            .setValue(ref)
                            .build();
                    constructorArgsList.add(constructorArgs);
                    continue;
                }

                //基本类型
                String type = item.getAttribute("type");
                String value = item.getAttribute("value");
                if ("java.lang.String".equalsIgnoreCase(type)) {
                    constructorArgs = new ConstructorArgs.Builder()
                            .setHasRef(false)
                            .setValue(value)
                            .setType(String.class)
                            .build();
                } else if ("java.lang.Integer".equalsIgnoreCase(type)) {
                    constructorArgs = new ConstructorArgs.Builder()
                            .setHasRef(false)
                            .setValue(Integer.valueOf(value))
                            .setType(Integer.class)
                            .build();
                }
                constructorArgsList.add(constructorArgs);
            }
        }
    }

}
